// pages/to_pay/to_pay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    onPay: true,  //是否启用支付
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var from = options.from;
    //订单来源购物车
    if (from == "Shopping_Cart") {
      this.fromShopcar(options.total)
      this.getAddress();
    }
    else {
      var id = options.id
      this.fromOrder(id)
    }

  },
  //从购物车跳转的购买详情页面
  fromShopcar: function (total) {
    var shopCar = wx.getStorageSync('shopCar'); //从缓存中获取购物车信息
    this.data.total = total; //获取订单金额

    this.setData({
      goodsList: shopCar,
      total: total

    })
  },
  //从我的订单详情中进入
  fromOrder: function (id) {
    if (id) {
      var that = this;
      wx.request({
        url: 'http://111.230.44.126:88/api/v1/order/' + id,
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          that.setData({
            orderStatus: res.data.status,
            goodsList: res.data.snap_items,
            total: res.data.total_price,
            basicInfo: {
              orderTime: res.data.create_time,
              orderNo: res.data.order_no
            }
          })
          var addressInfo = {
            name: res.data.snap_address.name,
            mobile: res.data.snap_address.mobile,
            totalDetail: that.setAddress(res.data.snap_address)
          };
          that.bindAddress(addressInfo)
        }
      });
      //将地址进行整合

    }
  },
  //下单后，支付成功或者失败后，点左上角返回时能够更新订单状态 所以放在onshow中
  onShow: function () {
    if (this.data.id) {
      this.fromOrder(this.data.id)
    }
  },
  //绑定地址
  bindAddress: function (addressInfo) {
    this.setData({
      addressInfo: addressInfo
    })
  },
  setAddress: function (res) {
    //拼合地址，若微信原生界面存在地址则显示，不存在则显示服务器数据库中的收货地址
    var province = res.provinceName || res.province,
      city = res.cityName || res.city,
      country = res.countyName || res.country,
      detail = res.detailInfo || res.detail;
    var totalDetail = city + country + detail;
    //直辖市，取出省部分
    if (!this.isCenterCity(province)) {
      totalDetail = province + totalDetail;
    };
    return totalDetail;
  },

  /*是否为直辖市*/
  isCenterCity(name) {
    var centerCitys = ['北京市', '天津市', '上海市', '重庆市'],
      flag = centerCitys.indexOf(name) >= 0;
    return flag;
  },
  getAddress: function () {
    var that = this;
    wx.request({
      url: 'http://111.230.44.126:88/api/v1/address',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res)
        var addressInfo = {
          name: res.data.name,
          mobile: res.data.mobile,
          totalDetail: that.setAddress(res.data)
        };
        that.bindAddress(addressInfo)
      }
    })
  },
  //保存收货地址
  submitAddress: function (res) {
    wx.request({
      url: 'http://111.230.44.126:88/api/v1/address',
      method: "post",
      data: {
        name: res.userName,
        mobile: res.telNumber,
        city: res.cityName,
        country: res.countyName,
        province: res.provinceName,
        detail: res.detailInfo,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function () {
        wx.showToast({
          title: "地址成功保存",
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        wx.showModal({
          title: '获取地址失败',
          content: res.errMsg,
          showCancel: false
        })
      }
    })
  },
  //下单去付款
  addOrder: function () {
    if (!this.data.addressInfo) {
      wx.showModal({
        title: '错误',
        content: '请先设置您的收货地址！',
        showCancel: false
      })
    }
    else {
      var orderInfo = [];
      var productInfo = this.data.goodsList;
      var that = this;
      for (let i = 0; i < productInfo.length; i++) {
        orderInfo.push({
          product_id: productInfo[i].id,
          count: productInfo[i].buyNumber
        })
      }
      wx.request({
        url: 'http://111.230.44.126:88/api/v1/order',
        method: 'post',
        data: { products: orderInfo },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token')
        },

        success: function (res) {
          //订单生成成功
          if (res.data.pass) {
            var id = res.data.order_id;
            that.setData({
              id: id,
            })
            that.pay(id)
          }
        }
      })



    }

  },
  //支付
  pay: function (id) {
    var orderNumber = id;
    var that = this;
    wx.removeStorageSync('shopCar');
    if (!this.data.onPay) {
      wx.showModal({
        title: '支付提示',
        content: '本产品仅用于演示，支付系统已屏蔽',
        showCancel: false
      })
    }
    else {
      wx.request({
        url: 'http://111.230.44.126:88/api/v1/pay/pre_order',
        method: 'post',
        data: { id: orderNumber },
        header: {
          "content-type": "application/json",
          "token": wx.getStorageSync("token")
        },
        success: function (res) {
          var timeStamp = res.timeStamp;
          var statusCode = res.statusCode;
          if (timeStamp) { //可以支付
            wx.requestPayment({
              'timeStamp': timeStamp.toString(),
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': data.signType,
              'paySign': data.paySign,
              success: function () {
                res.statusCode == 2;
              },
              fail: function () {
                res.statusCode == 1;
              }
            });
          }
          else {
            res.statusCode == 0
          }
          if (res.statusCode != 0) {
            statusCode == 2;
            wx.navigateTo({
              url: '../pay-result/pay-result?id=' + id + '&statusCode=' + statusCode + '&from=order',
            })
          }
        }
      })
    }
  }
})
